<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  
    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="../css/style.css">
	<script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
	<link rel="stylesheet" type="text/css" href="../js/bootstrap-fileinput/css/fileinput.min.css">
	<script src="../js/bootstrap-fileinput/js/fileinput.js"></script>
	<script src="../js/bootstrap-fileinput/js/locales/zh.js"></script>
	<link rel="stylesheet" href="../plugins/select2/select2.css" />
 <link rel="stylesheet" href="../plugins/select2/select2-bootstrap.css" />
    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="../plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="../plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="../plugins/kindeditor/lang/zh_CN.js"></script>
    
    
      
    
    
</head>

<body class="hold-transition skin-red sidebar-mini" >

            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">                       		
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>                                                        
                            </li>   
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>                                                        
                            </li>    
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>                                                        
                            </li>     
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>                                                        
                            </li>                       
                        </ul>
                        <!--tab头/-->
						
                        <!--tab内容-->
						<form id="myForm">
                        <div class="tab-content">

                            <!--表单内容-->
                            <div class="tab-pane active" id="home">
                                <div class="row data-type">                                  
								   <div class="col-md-2 title">商品分类</div>
									<div class="col-md-10 data"><table>
										<tr>
											<td>
												<select id="one" class="form-control" name="category1Id" onchange="selectItemCat(this.value,'two')" >
												</select>
											</td>
											<td>
												<select id="two" class="form-control select-sm" name="category2Id" onchange="selectItemCat(this.value,'three')" ></select>
											</td>
											<td>
												<select id="three" class="form-control select-sm" name="category3Id" onchange="selectBrand(this.value)"></select>
											</td>
											<td >
												模板ID:<span id="typeId" ></span>
											</td>
										</tr>
									</table>
									</div>
		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control" name="goodsName"  placeholder="商品名称" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select class="form-control" name="brandId" id="brandSelect"></select>
		                           </div>
		
								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control"  name="caption" placeholder="副标题" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" class="form-control" name="price" placeholder="价格" value="">
		                           	   </div>
		                           </div>
		                           
		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
                                       <textarea name="content" style="width:800px;height:400px;visibility:hidden;" ></textarea>
                                   </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               
		                           	<textarea rows="4"  class="form-control" name="packageList"   placeholder="包装列表"></textarea>
		                           </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4"  class="form-control" name="saleService"    placeholder="售后服务"></textarea>
		                           </div>                        
                                  
                                    
                                </div>
                            </div>
                            
                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">                                  
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <button type="button" class="btn btn-default" title="新建" onclick="removeCI()" data-target="#uploadModal"  data-toggle="modal"  ><i class="fa fa-file-o"></i> 新建</button>
                             		                 
					             </div>
								 
								 <table class="table table-bordered table-striped table-hover dataTable">
					                    <thead>
					                        <tr>
					                            
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
							            </thead>
					                    <tbody id="ciBody">

					                    </tbody>
								 </table> 
								  
                                </div>
                            </div>
                           
                           
                            <!--扩展属性-->
                            <div class="tab-pane" id="customAttribute">
                                <div class="row data-type" id="customId">

                                </div>
                            </div>
                      
                            <!--规格-->
                            <div class="tab-pane" id="spec">
                            	<div class="row data-type">
	                            	<div class="col-md-2 title">是否启用规格</div>
			                        <div class="col-md-10 data">
			                        	<input type="checkbox" onchange="specTF(this)">
			                        </div>
                            	</div>
                            	<p>
                            	
                            	<div>
                            	
	                                <div class="row data-type" id="specDiv">

	                                </div>
	
	                                
	                                <div class="row data-type">
										<table class="table table-bordered table-striped table-hover dataTable">
											<thead id="specName">
											</thead>
											<tbody id="specTable">

											</tbody>
										</table>
	                                </div>
	                                
	                            </div>
                            </div>
                            
                        </div>
						</form>
                        <!--tab内容/-->
						<!--表单内容/-->
							 
                    </div>
                 	
                 	
                 	
                 	
                   </div>
                  <div class="btn-toolbar list-toolbar">
				      <button class="btn btn-primary" onclick="addGoods()"  ><i class="fa fa-save"></i>保存</button>
				      <button class="btn btn-default" >返回列表</button>
				  </div>
			
            </section>
            

<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">
			
			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
		      		<td><input  class="form-control" id="addColor" placeholder="颜色" >  </td>
		      	</tr>			    
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<table>
							<tr>
								<td>
									<input type="hidden"  id="addImg">
									<input type="file" name="myFile" id="myFile" multiple>
					            </td>
								<td id="imgTB">

								</td>
							</tr>						
						</table>
		      		</td>
		      	</tr>		      	
			 </table>				
			
		</div>
		<div class="modal-footer">						
			<button class="btn btn-success"  data-dismiss="modal" aria-hidden="true" onclick="colorImg()">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>

            
            <!-- 正文区域 /-->
<script type="text/javascript">
	function removeCI(){
		$("#addColor").val("");
		$("#addImg").val("");
		$("#myFile").val("");
	}

	var editor;
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="content"]', {
			allowFileManager : true
		});
	});
	$(function (){
		selectItemCat(0,'one');

		$('#myFile').fileinput({
			language: 'zh', //设置语言
			uploadUrl: "/imgController/addImg", //上传的地址
			allowedFileExtensions : ['jpg', 'png','gif'],//接收的文件后缀,
			maxFileCount: 100,
			enctype: 'multipart/form-data',
			showUpload: true, //是否显示上传按钮
			showCaption: false,//是否显示标题
			browseClass: "btn btn-primary", //按钮样式
			previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
			msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
		}).on('fileuploaded',function (event,data,previewId,index){
			if(data.response != null){
				if(data.response.code == 100){
					$("#addImg").val(data.response.data);
				}

				if(data.response.code == 101){
					alert(data.response.data);
				}

			}
		})
	})
	function selectItemCat(parentId,obj){

		$.ajax({
			url:"/itemCatController/selectByParentId",
			type:"post",
			data:{parentId:parentId},
			dataType:"json",
			async:true,
			success:function (result){
				if(result.code == 100){
					var itemList = result.data;
					var selectHtml = '';
						selectHtml += '<option value="-1" >--请选择--</option>'
					for(var i = 0; i < itemList.length; i++){
						selectHtml += '<option value="'+itemList[i].id+'" >'+itemList[i].name+'</option>'
					}
					$("#" + obj).html(selectHtml);
					if(obj == "two"){
						$("#three").html("");
					}

				}
				if(result.code == 101){
					alert(result.message);
				}

			},
			error:function (){
				alert("查询异常");
			}
		})
	}

	function selectBrand(obj){
		$.ajax({
			url:"/typeTemplate/selectTemplate",
			type:"post",
			data:{id:obj},
			dataType:"json",
			success:function (result){
				if(result.code == 100){
					var itemCat = result.data.itemCat;
					var tbTypeTemplate = result.data.tbTypeTemplate;
					$("#typeId").text(itemCat.typeId);
					//alert(itemCat.typeId)
					var brandList = JSON.parse(tbTypeTemplate.brandIds);
					var brandOption = ''
						brandOption += '<option value="-1">--请选择--</option>'
					for(var i = 0;i < brandList.length; i++){
						brandOption += '<option value="'+brandList[i].id+'">'+brandList[i].text+'</option>'
					}
					$("#brandSelect").html(brandOption);

					var customList = JSON.parse(tbTypeTemplate.customAttributeItems);
					var customDiv = ''
					for(var i = 0; i < customList.length; i++){
						customDiv += '<div>'
							customDiv += '<div class="col-md-2 title">'+customList[i].text+'</div>'
							customDiv += '<div class="col-md-10 data">'
								customDiv += '<input class="form-control" name="'+customList[i].text+'" placeholder="'+customList[i].text+'">'
							customDiv += '</div>'
						customDiv += '</div>'
					}
					$("#customId").html(customDiv);

				}
				if(result.code == 101){
					alert(result.message);
				}
			},
			error:function (){
				alert("查询异常");
			}
		})
	}

	function addGoods(){
		var introduction = editor.html();
		var goodsColor = $("[name=goodsColor]").text();
		var goods = goodsColor.substring(1).split(' ');
		//获取颜色
		var image = '';
		var ci = []
		$("input[name=goodsImg]").each(function (i,e){
			if(i == 0){
				image = $(e).val();
			}
			ci.push({color:goods[i],url:$(e).val()})
		})
		alert(image)

		var b = $("#customId").find("input");
		var custom = $("#customId").children();
		var  custom_attribute_items = [];
		for(var i = 0; i < custom.length; i++){
			var text = $(custom[i]).children(":first").text();
			var value = $(custom[i]).find("input").val();
			custom_attribute_items.push({text:text,value:value});
		}
		var customAttributeItems = JSON.stringify(custom_attribute_items);

		var specList = $("#specDiv").children();
		var specification_items = [];
		for(var i = 0 ; i < specList.length; i++){
			var attributeName = $(specList[i]).children(":first").text();
			var attributeValue = [];
			$(specList[i]).find("input:checked").each(function (i,e){
				attributeValue.push($(e).val());
			})
			specification_items.push({attributeName:attributeName,attributeValue:attributeValue});
		}
		var specificationItems = JSON.stringify(specification_items);

		var items = [];
		var itemList = $("#specTable").children();
		var speclist = $("#specName").children(":first");
		var specName = $(speclist).children();
		for(var i = 0; i < itemList.length; i++){
			var specList = $(itemList[i]).find("select[name=spec]");
			var title = "";
			var spec = {};
			for(var j= 0; j < specList.length; j++ ){
				title += specList[j].value;
				var key = $(specName[j]).text();
				var value = specList[j].value;
				spec[key] = value;
			}
			title += $("input[name = goodsName]").val();
			var price =$(itemList[i]).find("input[name=price]").val();
			var num = $(itemList[i]).find("input[name=num]").val();
			var categoryId = $("#three").val();
			items.push({title:title,sellPoint:introduction,price:price,num:num,categoryid:categoryId,status:1,spec:spec,createTime:new Date(),updateTime:new Date(),image:image});
			var itemString =JSON.stringify(items);
		}
		var cust = []
		for(var i = 0; i < b.length; i++){
			cust.push({text:b[i].name,value:b[i].value})
		}
		var c =JSON.stringify(cust);
		var itemImages = JSON.stringify(ci);
		$.ajax({
			url:"/goodsEditController/addGoods",
			type:"post",
			data:$("#myForm").serialize() +"&itemImages="+itemImages +"&introduction="+introduction + "&customAttributeItems=" + customAttributeItems +"&specificationItems=" + specificationItems +"&itemString=" +itemString,
			dataType:"json",
			success:function (result){
				if(result.code == 100){
					alert("增加成功");
				}
				if(result.code == 101){
					alert(result.message);
				}
			},
			error:function (){
				alert("增加失败");
			}
		})
	}

	function colorImg(){
		if($("#addColor").val().length <= 0){
			alert("请填写颜色");
			return ;
		}
		if($("#addImg").val().length <= 0){
			alert("请上传图片");
			return ;
		}
		var table = ''
			table += '<tr>'
			table += '<td name="goodsColor">'+' '+$("#addColor").val()+'</td>'
			table += '<td>'
			table += '<input type="hidden" name="goodsImg" value="'+$("#addImg").val()+'">'
			table += '<img src="'+$("#addImg").val()+'" width="100px" height="100px">'
			table += '</td>'
		table += '<td> <button type="button" class="btn btn-default" title="删除" onclick="removeTr(this)"><i class="fa fa-trash-o"></i> 删除</button></td>'
	table += '</tr>'
		$("#ciBody").append(table);
	}

function removeTr(obj){
		$(obj).parents("tr:first").remove();
}

function specBox(){
		var s = $("#specDiv").children();
		$("#specTable").children().remove();
		if($(s).find("input:checked").length > 0){
			var spec = ''
			spec += '<tr>'
			for(var i = 0; i < s.length; i++){
				if($(s[i]).find("input:checked").length > 0){
					spec += '<th class="sorting">'+$(s[i]).children(":first").text()+'</th>'
				}
			}
			spec += '<th class="sorting">价格</th>'
			spec += '<th class="sorting">库存</th>'
			spec += '<th class="sorting">是否启用</th>'
			spec += '<th class="sorting">是否默认</th>'
			spec += '</tr>'
			$("#specName").html(spec);
			var specTable = ''
			specTable += '<tr>'
			var b = 1;
			for(var i = 0; i < s.length; i++){
				//s为用户选中的规格
				b *= $("[name=spec"+i+"]:checked").length;

				if($(s[i]).find("input:checked").length > 0){
					specTable += '<td>'
					specTable += '<select name="spec">'
					$("[name=spec"+i+"]:checked").each(function (i,e){
						specTable += '<option value="'+$(e).val()+'">'+$(e).val()+'</option>'
					})
					specTable += '</select>'
					specTable += '</td>'
				}

			}
			specTable += '<td><input class="form-control" name="price"  placeholder="价格"></td>'
			specTable += '<td><input class="form-control" name="num" placeholder="库存数量"></td>'
			specTable += '<td><input type="checkbox" name="using" ></td>'
			specTable += '<td><input type="checkbox" name="isDefault"></td>'
			if(b > 0){
				for(var i = 0; i < b; i++){
					$("#specTable").append(specTable);
				}
			}else {
				$("#specTable").append(specTable);
			}


		}else {
			$("#specName").children().remove();
		}


}

function specTF(obj){
	if($(obj).prop("checked")){
		$.ajax({
			url:"/typeTemplate/selectSpec",
			type:"post",
			data:{id:$("#typeId").text()},
			dataType:"json",
			success:function (result){
				if(result.code == 100){
					var specVoList = result.data;
					var specDiv = ''
					for(var i = 0; i < specVoList.length; i++){
						specDiv += '<div name="specificationName">'
						specDiv += '<div class="col-md-2 title">'+specVoList[i].specName+'</div>'
						specDiv += '<div class="col-md-10 data">'
						var specOpList = specVoList[i].specOption;
						for(var j = 0; j < specOpList.length; j++){
							specDiv += '<span>'
							specDiv += '<input  type="checkbox" name="spec'+i+'" onchange="specBox()" value="'+specOpList[j].optionName+'">' +specOpList[j].optionName
							specDiv += '</span>'
						}
						specDiv += '</div>'
						specDiv += '</div>'
					}
					$("#specDiv").html(specDiv);
				}
				if(result.code == 101){
					alert("查询失败");
				}
			},
			error:function (){
				alert("查询失网络异常");
			}
		})
	}else{
		$("#specDiv").children().remove();
		$("#specTable").children().remove();
		$("#specName").children().remove();
	}

}

/*	var items = [];
	//勾选规格选项复选框函数
	function checkSpec(event,name,value){
		//调用方法判断原集合中是否已有attributeName
		var obj = searchObjectByKey(items,'attributeName',name);
		if(obj != null){
			if($(event).prop('checked')){//勾选
				//如果之前有数据，往原有的对象中追加
				obj.attributeValue.push(value);
			}else{//取消勾选
				obj.attributeValue.splice(obj.attributeValue.indexOf(value),1)//从items中移除规格选项
				//如果规格选项没有数据了
				if(obj.attributeValue.length==0){
					//移除items中的数据
					items.splice(items.indexOf(obj),1)
				}
			}
		}else{
			//如果之前没有数据，items新加数据
			items.push({'attributeName':name,'attributeValue':[value]});
		}
		console.log(items);
		//后续调用，这里先不调用，后续选择之后组装选择后的数据用的
		createSLKUList(event);
	}
	//遍历组装用户勾选规格选项数据
	function searchObjectByKey(list,attributeName,attributeValue){
		for(var i=0;i<list.length;i++){
			//如果list中我们选择key存在
			if(list[i][attributeName] == attributeValue){
				return list[i];//返回当前对象
			}
		}
		//遍历结束后都不存在，返回null
		return null;
	}
	//创建初始化值
		var itemList = [ { spec: {} } ];
		//创建SKU列表
		function createSLKUList(event) {
			//创建初始化值
			itemList=[{spec:{}}];
			//遍历items 拆除里面的数据
			for (var i=0;i<items.length;i++){
				itemList=addColum(itemList,items[i].attributeName,items[i].attributeValue);
			}
			//  $("#mysan").html(JSON.stringify(itemList));
			//拼接表格
			if($(event).prop("checked")) {
				var html = '';
				html += '<thead>';
				html += '<tr>';
				for (var i = 0; i < items.length; i++) {
					html += '<th class="sorting">' + items[i].attributeName + '</th>';
				}
				html += '<th class="sorting">价格</th>';
				html += '<th class="sorting">库存</th>';
				html += '<th class="sorting">是否启用</th>';
				html += '<th class="sorting">是否默认</th>';
				html += '</tr>';
				html += '</thead>';
				html += '<tbody id="tbody">';
				for (var j = 0; j < itemList.length; j++) {
					html += '<tr>';
					for (var k = 0; k < items.length; k++) {
						html += '<td>' + itemList[j].spec[items[k].attributeName] + '</td>';
					}
					html += '<td>';
					html += '<input class="form-control" name="price"  placeholder="价格">';
					html += '</td>';
					html += '<td>';
					html += '<input class="form-control" name="num"  placeholder="库存数量">';
					html += '</td>';
					html += '<td>';
					html += '<input type="checkbox" name="using" value="1">';
					html += '</td>';
					html += '<td>';
					html += '<input type="checkbox" name="isDefault" value="1">';
					html += '</td>';
					html += '</tr>';
				}
				html += '</tbody>';
				$("#specTable").html(html);
			}else{
				items = [];
				itemList = [{spec:{}}];
				$("#dataType").find("input").each(function (i,e) {
					if($(e).prop("checked")){
						$(e).prop("checked",!$(e).prop("checked"))
					}
				})
				$("#specTable").empty();
			}
		}
		//提取拼接表头和数据
		function addColum(list,attributeName,attributeValue){
			var newList = [];
			for(var i = 0; i < list.length; i++){
				var oldRow = list[i];
				for(var j=0; j < attributeValue.length; j++){
					var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
					newRow.spec[attributeName] = attributeValue[j];
					newList.push(newRow)
				}
			}
			return newList;
		}

		//添加表格的列
		function addColum(list,columName,columValues) {
			//定义新集合接收行
			var newList = [];
			for(var i = 0; i < list.length; i++){
				var oldRow = list[i];
				for(var j=0; j < columValues.length; j++){
					var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
					newRow.spec[columName] = columValues[j];
					newList.push(newRow)
				}
			}
			console.log(newList);
			return newList;
		}*/
</script>
       
</body>

</html>